package cn.devnotes.servletdemo.controller;

import cn.devnotes.servletdemo.util.AppConfigUtil;
import cn.devnotes.servletdemo.util.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/login")
public class LoginController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String driver = AppConfigUtil.get("jdbc.driverClassName");
        String url = AppConfigUtil.get("jdbc.url");
        String userName = AppConfigUtil.get("jdbc.username");
        String password = AppConfigUtil.get("jdbc.password");
        Connection conn = DbUtil.getConnection(driver, url, userName, password);

        String sql = "select * from `demo_user` where user_name = ? limit 1";
        try {
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, "chenyong");
            ResultSet resultSet = stmt.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String uName = resultSet.getString("user_name");
                String uPwd = resultSet.getString("password");
                response.getWriter().println("id : " + id + ", username : " + uName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
